package com.yy.socket.handler;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.utils.lock.SetWithLock;

import com.alibaba.fastjson.JSON;
import com.yy.ant.chat.entity.Chatmessage;
import com.yy.ant.chat.service.IChatmessageService;
import com.yy.model.ReceiveMessage;
import com.yy.model.SendMessage;
import com.yy.socket.Type;
import com.yy.utils.SocketMsgUtils;

/**
 * 处理点对点消息
 * 
 * @author Lenovo
 *
 */
@Service
public class P2PMessageHandler implements MsgHandlerInterface {

	@Autowired
	private IChatmessageService iChatmessageService;

	@Override
	public Object handler(String text, ChannelContext context) {
		// 解析消息内容
		ReceiveMessage msgData = JSON.parseObject(text, ReceiveMessage.class);
		Map<String, String> to = msgData.getTo();
		Map<String, String> mine = msgData.getMine();
		String id = to.get("id");
		// String type = msgData.getAction();
		// t-io支持多点登录,获取的是一个集合,因为此账号可能存在多个连接哦
		SetWithLock<ChannelContext> contexts = Tio.getByUserid(context.getTioConfig(), id);
		if (contexts != null && contexts.size() > 0) {
			SendMessage sendMessage = new SendMessage();
			sendMessage.setUsername(mine.get("username"));
			sendMessage.setAvatar(mine.get("avatar"));
			sendMessage.setId(mine.get("id"));
			sendMessage.setType("friend");
			sendMessage.setContent(mine.get("content"));
			sendMessage.setFromid(mine.get("id"));
			sendMessage.setTimestamp(System.currentTimeMillis());
			String strJson = JSON.toJSONString(sendMessage);
			// 发送消息,记得转成json
			try {
				for (ChannelContext con : contexts.getObj()) {
					Tio.send(con, SocketMsgUtils.madeWsResponse(Type.P2P_REQ, strJson));
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				// 存储消息
				Chatmessage cm = new Chatmessage();
				cm.setUsername(mine.get("username"));
				cm.setAvatar(mine.get("avatar"));
				cm.setContent(mine.get("content"));
				cm.setFroms(Long.valueOf(mine.get("id")));
				cm.setTimestamp(System.currentTimeMillis());
				cm.setToid(Long.valueOf(to.get("id")));
				cm.setType(1);
				cm.setUnreadpoint(0); // 0.已读,1.未读 cm.setUsername(mine.get("username"));
				iChatmessageService.save(cm);

			}
		} else {
			System.out.print("对方不在线,存储离线消息");
			// 对方不在线,存储离线消息

			Chatmessage cm = new Chatmessage();
			cm.setUsername(mine.get("username"));
			cm.setAvatar(mine.get("avatar"));
			cm.setContent(mine.get("content"));
			cm.setFroms(Long.valueOf(mine.get("id")));
			cm.setTimestamp(System.currentTimeMillis());
			cm.setToid(Long.valueOf(to.get("id")));
			cm.setType(1);
			cm.setUnreadpoint(1);// 0.已读,1.未读 cm.setUsername(mine.get("username"));
			iChatmessageService.save(cm);

		}

		return null;
	}

}
